package com.kjcxlab.avcviewer.network;

import android.content.Context;


import com.kjcxlab.avcviewer.player.IntegrateListener;
import com.kjcxlab.avcviewer.util.Constants;
import com.kjcxlab.avcviewer.util.Logger;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * Created by eshixia on 8/12/2015.
 */
public class RtpReceiver {
    private MulticastSocket mSocket = null;
    private DatagramPacket mPacket;
    private InetAddress multicastGroup = null;
    private IntegrateListener mRtpListener = null;
    private byte[] data = new byte[1500];

    public boolean RtpReceiver(int localPort, IntegrateListener listener) {
        try {
            mRtpListener = listener;
            mSocket = new MulticastSocket(localPort);
            multicastGroup = InetAddress.getByName(Constants.ADDRESS);
            mSocket.joinGroup(multicastGroup);
            mPacket = new DatagramPacket(data, data.length);
        } catch (java.net.SocketException e) {
            Logger.d(e.toString());
        } catch (java.io.IOException e) {
            Logger.d(e.toString());
        }

        return true;
    }

    public void start(){
        new Thread(new Receiver()).start();
    }

    public void release() {
        try {
            mSocket.leaveGroup(multicastGroup);
            mSocket.close();
            mSocket = null;
            Logger.d("UdpThread has stopped");
        } catch (IOException e) {
            Logger.d(e.toString());
        }
    }

    class Receiver implements Runnable {

        @Override
        public void run() {
            while (true) {
                int length = 0;
                try {
                    mSocket.receive(mPacket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if ((length = mPacket.getLength()) > 0) {
                    byte[] buf = new byte[length];
                    System.arraycopy(mPacket.getData(), mPacket.getOffset(), buf, 0, length);
                    mRtpListener.integrateOneFrame(buf);
                }
            }
        }
    }

}
